<template>
	<view class="charging-progress-container">
		<!-- 自定义导航栏 -->
		<custom-navbar title="充电中" backgroundColor="#42a5f5" titleColor="#ffffff"></custom-navbar>

		<!-- 充电信息卡片 -->
		<view class="charging-card" style="margin-top: 80px;">


			<!-- 充电进度圆环 - 简化实现 -->
			<view class="progress-circle-wrapper">
				<view class="progress-circle">
					<view class="progress-circle-bg"></view>
					<view class="progress-circle-bar" :style="{ transform: `rotate(${progressDegrees}deg)` }"></view>
					<view class="progress-circle-text">
						<text class="charging-status">正在充电</text>
						<text class="progress-percent">{{ Math.floor(chargingProgress) }}%</text>
						<!-- <text class="elapsed-time">已充时长：{{ chargingData.duration || '25分钟' }}</text> -->
					</view>
				</view>
			</view>

			<!-- 能源统计信息 -->
			<view class="energy-stats">
				<view class="stat-item">
					<view class="stat-value">{{ chargingData.chargedPower || '12.5' }} 度</view>
					<view class="stat-label">已充电量</view>
				</view>
				<view class="stat-divider"></view>
				<view class="stat-item">
					<view class="stat-value">¥{{ chargingData.cost || '22.50' }}</view>
					<view class="stat-label">预估费用</view>
				</view>
			</view>

			<!-- 充电参数 -->
			<view class="charging-params">
				<view class="param-item">
					<view class="param-header">
						<text class="param-label">充电功率：</text>
						<text class="param-value">{{ chargingData.power }} W</text>
					</view>
					<view class="power-progress-bar">
						<view class="power-progress" :style="{ width: chargingData.powerPercentage + '%' }"></view>
					</view>
				</view>

				<view class="param-item">
					<text class="param-label">当前电压：</text>
					<text class="param-value">{{ chargingData.voltage }} V</text>
				</view>

				<view class="param-item">
					<text class="param-label">当前电流：</text>
					<text class="param-value">{{ chargingData.current }} A</text>
				</view>
			</view>
		</view>
		<!-- 停止充电按钮 -->
		<view class="stop-btn" @tap="stopCharging" :class="{ 'stop-btn-disabled': isStoppingCharging }">
			<text>{{ stopChargingText }}</text>
		</view>

		<!-- 停止充电弹框 -->
		<view class="charging-overlay" v-if="isStoppingCharging">
			<view class="charging-modal">
				<view class="modal-header">
					<text>正在停止充电</text>
				</view>
				<view class="modal-content">
					<view class="progress-circle-container">
						<view class="progress-circle">
							<view class="circle-bg"></view>
							<view class="progress" :style="{ transform: `rotate(${stopProgressDegrees}deg)` }"></view>
							<view class="mask" v-if="stopProgressPercent / 100 > 0.5"></view>
							<view class="inner-circle">
								<text class="countdown">{{ Math.max(0, Math.floor(stopCountdown)) }}</text>
								<text class="countdown-label">秒</text>
							</view>
						</view>
					</view>
					<view class="status-message">
						<text>充电桩停止中，请稍候...</text>
					</view>
					<view class="progress-steps">
						<view class="step" :class="{ active: stopProgressPercent >= 10 }">
							<view class="step-dot"></view>
							<text>断开连接</text>
						</view>
						<view class="step" :class="{ active: stopProgressPercent >= 30 }">
							<view class="step-dot"></view>
							<text>结束计费</text>
						</view>
						<view class="step" :class="{ active: stopProgressPercent >= 60 }">
							<view class="step-dot"></view>
							<text>关闭电源</text>
						</view>
						<view class="step" :class="{ active: stopProgressPercent >= 90 }">
							<view class="step-dot"></view>
							<text>完成</text>
						</view>
					</view>
				</view>

			</view>
		</view>
	</view>
</template>

<script>
import { chargingProgressApi } from '@/src/api/chargingProgress.js'
import CustomNavbar from '@/components/CustomNavbar.vue'

export default {
	components: {
		CustomNavbar
	},
	data() {
		return {
			chargingData: {
				stationId: 'GZ-2023-1265',
				mode: '快速充电',
				power: 145,
				powerPercentage: 55, // 功率进度条百分比
				voltage: 380,
				current: 380,
				startTime: '今天 14:30',
				duration: '25分钟',
				chargedPower: '12.5', // 已充电量（度）
				cost: '22.50' // 预估费用（元）
			},
			chargingProgress: 1, // 充电进度百分比
			animationTimer: null,

			// 状态相关
			charingPilesSn: '', // 设备ID
			socketSn: '', // 充电枪编号
			dataUpdateTimer: null, // 数据更新定时器
			showDebugInfo: false, // 是否显示调试信息
			stopChargingText: '停止充电',
			isCharging: true, // 充电状态标志

			// 停止充电相关
			isStoppingCharging: false, // 是否正在停止充电
			stopProgressTimer: null, // 停止充电进度计时器
			stopProgressPercent: 0, // 停止充电进度百分比
			stopChargingTimeout: null, // 停止充电超时计时器
			stopRequestTime: 50, // 停止充电需要的时间（秒）
			stopCountdown: 50 // 停止充电倒计时（秒）
		}
	},
	computed: {
		// 计算充电进度的旋转角度
		progressDegrees() {
			// 将百分比转换为角度，最大只转90度（因为只显示右上角的弧）
			return (this.chargingProgress / 100) * 90;
		},
		// 停止充电进度角度
		stopProgressDegrees() {
			// 将百分比转换为角度 (0-360度)
			return (this.stopProgressPercent / 100) * 360;
		}
	},
	onLoad(options) {
		// 获取设备ID
		this.charingPilesSn = options.charingPilesSn || this.$store.state.charger.charingPilesSn;
		this.socketSn = options.socketSn || this.$store.state.charger.socketSn;

		// 启动进度条动画
		this.startProgressAnimation();

		// 开始实时查询充电状态
		this.startRealTimeStatusQuery();
	},
	onUnload() {
		// 组件销毁时清除所有定时器
		this.clearAllTimers();
	},
	methods: {
		// 返回上一页
		goBack() {
			if (this.isCharging) {
				uni.showModal({
					title: '提示',
					content: '充电正在进行中，确定要离开吗？',
					success: (res) => {
						if (res.confirm) {
							this.clearAllTimers();
							uni.navigateBack();
						}
					}
				});
			} else {
				uni.navigateBack();
			}
		},

		// 清除所有定时器
		clearAllTimers() {
			if (this.animationTimer) {
				clearInterval(this.animationTimer);
				this.animationTimer = null;
			}

			if (this.dataUpdateTimer) {
				clearInterval(this.dataUpdateTimer);
				this.dataUpdateTimer = null;
			}

			if (this.stopProgressTimer) {
				clearInterval(this.stopProgressTimer);
				this.stopProgressTimer = null;
			}

			if (this.stopChargingTimeout) {
				clearTimeout(this.stopChargingTimeout);
				this.stopChargingTimeout = null;
			}
		},

		// 启动进度条动画 - 每5秒增加1%
		startProgressAnimation() {
			this.chargingProgress = 1; // 初始进度从1%开始

			// 设置定时器，每5秒更新一次进度
			this.animationTimer = setInterval(() => {
				if (!this.isCharging) {
					// 如果未充电，进度条保持不变
					return;
				}

				// 每次精确增加1%，直到最大值99%
				if (this.chargingProgress < 99) {
					// 增加1%
					this.chargingProgress += 1;
				}
			}, 5000); // 5秒更新一次
		},

		// 开始实时查询充电状态
		startRealTimeStatusQuery() {
			// 立即执行一次查询
			this.queryOperationStatus();

			// 设置定时器，每5秒查询一次，与百分比更新同步
			this.dataUpdateTimer = setInterval(() => {
				if (!this.isCharging) return;
				this.queryOperationStatus();
			}, 3000);
		},

		// 查询充电状态
		queryOperationStatus() {
			const params = {
				charingPilesSn: this.charingPilesSn,
				socketSn: this.socketSn
			};

			chargingProgressApi.opretionStatus(params)
				.then(res => {
					if (res.code === 200 && res.data) {
						// 更新充电数据
						this.chargingData.voltage = res.data.voltage || 0;
						this.chargingData.current = res.data.current || 0;
						this.chargingData.power = res.data.power || 0;

						// 计算功率百分比 (假设最大功率为500W)
						this.chargingData.powerPercentage = Math.min(Math.floor(this.chargingData.power / 5), 100);
					}
				})
				.catch(err => {
					console.error('查询充电状态失败:', err);
				});
		},

		// 停止充电
		stopCharging() {
			// 如果已经在处理停止充电请求，则不再重复操作
			if (this.isStoppingCharging) return;

			// 显示停止充电确认弹窗
			uni.showModal({
				title: '确认停止充电',
				content: '确定要停止当前充电吗？',
				success: (res) => {
					if (res.confirm) {
						this.startStopChargingProcess();
					}
				}
			});
		},

		// 开始停止充电流程
		startStopChargingProcess() {
			// 设置状态为正在停止充电
			this.isStoppingCharging = true;
			this.stopChargingText = '正在停止充电';
			this.stopProgressPercent = 0;
			this.stopCountdown = this.stopRequestTime;

			// 启动进度条动画
			this.startStopProgressAnimation();

			// 发送停止充电请求
			const params = {
				charingPilesSn: this.charingPilesSn
			};

			chargingProgressApi.endCharging(params)
				.then(res => {
					// 清除进度动画
					this.clearStopProgressAnimation();

					if (res.code === 200) {
						// 停止充电成功
						this.isCharging = false;
						this.isStoppingCharging = false;
						this.stopChargingText = '已停止充电';

						// 重置数据
						this.chargingProgress = 0;

						// 跳转订单页面
						uni.navigateTo({
							url: '/pages/paymentOrder/payment0rder'
						});
					} else {
						// 停止充电失败
						this.handleStopChargingFailure(res.msg || '未知错误');
					}
				})
				.catch(err => {
					// 清除进度动画
					this.clearStopProgressAnimation();

					// 处理错误
					console.error('停止充电失败:', err);
					this.handleStopChargingFailure(err.message || '网络异常');
				});

			// 设置超时处理（60秒）
			this.stopChargingTimeout = setTimeout(() => {
				if (this.isStoppingCharging) {
					// 如果60秒后仍在停止充电状态，则认为超时
					this.clearStopProgressAnimation();
					this.handleStopChargingFailure('请求超时');
				}
			}, 60000);
		},

		// 启动停止充电进度动画
		startStopProgressAnimation() {
			// 清除可能存在的定时器
			if (this.stopProgressTimer) {
				clearInterval(this.stopProgressTimer);
			}

			// 创建新的定时器，每100ms更新一次进度，总计50秒完成
			const totalTime = this.stopRequestTime * 1000; // 50秒
			const interval = 100; // 100ms更新一次
			const increment = (interval / totalTime) * 100;
			const countdownDecrement = interval / 1000;

			this.stopProgressTimer = setInterval(() => {
				if (this.stopProgressPercent < 100) {
					this.stopProgressPercent += increment;
					this.stopCountdown -= countdownDecrement;

					if (this.stopProgressPercent > 100) {
						this.stopProgressPercent = 100;
					}

					if (this.stopCountdown < 0) {
						this.stopCountdown = 0;
					}
				} else {
					clearInterval(this.stopProgressTimer);
				}
			}, interval);
		},

		// 清除停止充电进度动画
		clearStopProgressAnimation() {
			if (this.stopProgressTimer) {
				clearInterval(this.stopProgressTimer);
				this.stopProgressTimer = null;
			}

			if (this.stopChargingTimeout) {
				clearTimeout(this.stopChargingTimeout);
				this.stopChargingTimeout = null;
			}

			this.stopProgressPercent = 100;
			this.stopCountdown = 0;
		},

		// 取消停止充电
		cancelStopCharging() {
			uni.showModal({
				title: '提示',
				content: '确定要取消停止充电操作吗？',
				success: (res) => {
					if (res.confirm) {
						// 清除定时器
						this.clearStopProgressAnimation();

						// 重置状态
						this.isStoppingCharging = false;
						this.stopChargingText = '停止充电';

						// 显示提示
						uni.showToast({
							title: '已取消停止充电',
							icon: 'none',
							duration: 1500
						});
					}
				}
			});
		},

		// 处理停止充电失败情况
		handleStopChargingFailure(errorMsg) {
			this.isStoppingCharging = false;
			this.stopChargingText = '停止充电';

			// 显示错误提示
			uni.showModal({
				title: '停止充电失败',
				content: `无法停止充电: ${errorMsg}，请稍后重试或联系客服。`,
				showCancel: false
			});
		}
	}
}
</script>

<style lang="scss">
.charging-progress-container {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	display: flex;
	flex-direction: column;
	height: 100vh;
	background-color: #f5f5f5;
	overflow: hidden;
	padding-bottom: 120px;
	/* Add bottom padding to prevent overlap with TabBar */
}

.charging-card {
	margin: 80px 20px 30px;
	background-color: #fff;
	border-radius: 16px;
	box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
	padding: 24px;
	animation: fadeIn 0.6s ease-out;
}

@keyframes fadeIn {
	from {
		opacity: 0;
		transform: translateY(20px);
	}

	to {
		opacity: 1;
		transform: translateY(0);
	}
}

.charging-info {
	background-color: #f9f9f9;
	border-radius: 12px;
	padding: 18px;
	margin-bottom: 24px;

	.info-item {
		display: flex;
		font-size: 15px;
		margin-bottom: 14px;

		&:last-child {
			margin-bottom: 0;
		}

		.info-label {
			color: #555;
			min-width: 90px;
			font-weight: 500;
		}

		.info-value {
			color: #333;
			font-weight: 500;
		}
	}
}

/* Energy Statistics Section */
.energy-stats {
	display: flex;
	justify-content: space-around;
	align-items: center;
	background-color: #f0f9ff;
	border-radius: 12px;
	padding: 20px 16px;
	margin-bottom: 24px;

	.stat-item {
		flex: 1;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;

		.stat-value {
			font-size: 22px;
			font-weight: bold;
			color: #42a5f5;
			margin-bottom: 6px;
		}

		.stat-label {
			font-size: 14px;
			color: #666;
		}
	}

	.stat-divider {
		width: 1px;
		height: 40px;
		background-color: #ddd;
	}
}

/* 圆环进度条样式优化 */
.progress-circle-wrapper {
	display: flex;
	justify-content: center;
	margin: 36px 0;

	.progress-circle {
		position: relative;
		width: 220px;
		height: 220px;

		.progress-circle-bg {
			position: absolute;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
			border-radius: 50%;
			border: 18px solid #f0f0f0;
			box-sizing: border-box;
		}

		.progress-circle-bar {
			position: absolute;
			top: 0;
			left: 0;
			width: 50%;
			height: 100%;
			overflow: hidden;
			transform-origin: center right;
			transition: transform 0.5s ease-out;

			&:before {
				content: '';
				position: absolute;
				top: 0;
				left: 0;
				width: 200%;
				height: 100%;
				border-radius: 50%;
				border: 18px solid #42a5f5;
				box-sizing: border-box;
				transform-origin: center right;
			}
		}

		.progress-circle-text {
			position: absolute;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;

			.charging-status {
				font-size: 18px;
				color: #333;
				font-weight: 500;
				margin-bottom: 8px;
			}

			.progress-percent {
				font-size: 46px;
				font-weight: bold;
				color: #42a5f5;
				line-height: 1.2;
			}

			.elapsed-time {
				font-size: 14px;
				color: #666;
				margin-top: 8px;
			}
		}
	}
}

.charging-params {
	background-color: #f9f9f9;
	border-radius: 12px;
	padding: 18px;

	.param-item {
		margin-bottom: 20px;

		&:last-child {
			margin-bottom: 0;
		}

		.param-header {
			display: flex;
			justify-content: space-between;
			font-size: 15px;
			margin-bottom: 10px;

			.param-label {
				color: #555;
				font-weight: 500;
			}

			.param-value {
				color: #333;
				font-weight: 500;
			}
		}

		.param-label {
			width: 90px;
			color: #555;
			font-size: 15px;
			font-weight: 500;
		}

		.param-value {
			color: #333;
			font-size: 15px;
			font-weight: 500;
		}
	}

	.power-progress-bar {
		width: 100%;
		height: 8px;
		background-color: #e8e8e8;
		border-radius: 8px;
		overflow: hidden;

		.power-progress {
			height: 100%;
			background-color: #42a5f5;
			border-radius: 8px;
			transition: width 0.8s ease-in-out;
		}
	}
}

.stop-btn {
	margin: 30px 20px 100px;
	height: 50px;
	line-height: 50px;
	background-color: #ff6b00;
	color: #fff;
	border-radius: 50px;
	display: flex;
	justify-content: center;
	align-items: center;
	font-size: 18px;
	font-weight: 500;
	box-shadow: 0 4px 10px rgba(255, 107, 0, 0.3);
	animation: fadeIn 0.8s ease-out;

	&:active {
		transform: scale(0.98);
		background-color: #e86000;
	}

	&.stop-btn-disabled {
		background-color: #ccc;
		box-shadow: none;

		&:active {
			transform: none;
		}
	}
}

/* 充电启动/停止弹框样式 */
.charging-overlay {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0, 0, 0, 0.5);
	display: flex;
	justify-content: center;
	align-items: center;
	z-index: 999;
	animation: fadeInOverlay 0.3s ease-out;
}

@keyframes fadeInOverlay {
	from {
		opacity: 0;
	}

	to {
		opacity: 1;
	}
}

.charging-modal {
	width: 90%;
	max-width: 600rpx;
	background-color: #fff;
	border-radius: 20px;
	overflow: hidden;
	box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
	display: flex;
	flex-direction: column;
	animation: scaleIn 0.3s ease-out;
}

@keyframes scaleIn {
	from {
		opacity: 0;
		transform: scale(0.9);
	}

	to {
		opacity: 1;
		transform: scale(1);
	}
}

.modal-header {
	padding: 22px 0;
	text-align: center;
	font-size: 18px;
	font-weight: 500;
	background-color: #ff6b00;
	color: #fff;
}

.modal-content {
	padding: 30px 20px;
	display: flex;
	flex-direction: column;
	align-items: center;
}

.progress-circle-container {
	position: relative;
	width: 200rpx;
	height: 200rpx;
	margin-bottom: 24px;
}

.progress-circle {
	position: relative;
	width: 100%;
	height: 100%;
}

.circle-bg {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	border: 6px solid #f0f0f0;
	border-radius: 50%;
	box-sizing: border-box;
}

.progress {
	position: absolute;
	top: 0;
	left: 0;
	width: 50%;
	height: 100%;
	border-radius: 100px 0 0 100px;
	background-color: transparent;
	transform-origin: right center;
	transform: rotate(0deg);
	z-index: 2;
	overflow: hidden;
	transition: transform 0.3s linear;

	&::before {
		content: '';
		position: absolute;
		top: -6px;
		left: -6px;
		width: 200%;
		height: 100%;
		border: 6px solid #ff6b00;
		border-radius: 50%;
		box-sizing: content-box;
	}
}

.mask {
	position: absolute;
	top: 0;
	left: 50%;
	width: 50%;
	height: 100%;
	background-color: transparent;
	z-index: 3;

	&::before {
		content: '';
		position: absolute;
		top: -6px;
		left: -6px;
		width: 200%;
		height: 100%;
		border: 6px solid #ff6b00;
		border-radius: 50%;
		box-sizing: content-box;
	}
}

.inner-circle {
	position: absolute;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
	width: 70%;
	height: 70%;
	background-color: #fff;
	border-radius: 50%;
	z-index: 4;
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
}

.countdown {
	font-size: 40rpx;
	font-weight: bold;
	color: #ff6b00;
	line-height: 1;
}

.countdown-label {
	font-size: 24rpx;
	color: #999;
	margin-top: 4rpx;
}

.status-message {
	text-align: center;
	margin-bottom: 24px;
	font-size: 16px;
	color: #333;
}

.progress-steps {
	width: 100%;
	display: flex;
	justify-content: space-between;
	margin-bottom: 24px;
}

.step {
	display: flex;
	flex-direction: column;
	align-items: center;
	width: 20%;

	.step-dot {
		width: 20rpx;
		height: 20rpx;
		border-radius: 50%;
		background-color: #ddd;
		margin-bottom: 10rpx;
		transition: all 0.3s;
	}

	text {
		font-size: 22rpx;
		color: #999;
		text-align: center;
		transition: all 0.3s;
	}

	&.active {
		.step-dot {
			background-color: #ff6b00;
			box-shadow: 0 0 10rpx rgba(255, 107, 0, 0.5);
		}

		text {
			color: #ff6b00;
			font-weight: 500;
		}
	}
}

.modal-footer {
	padding: 18px;
	display: flex;
	flex-direction: column;
	align-items: center;

	text {
		font-size: 12px;
		color: #999;
		margin-bottom: 12px;
	}

	.cancel-btn {
		padding: 10px 40px;
		background-color: #f5f5f5;
		color: #666;
		font-size: 14px;
		border-radius: 30px;
		font-weight: 500;

		&:active {
			opacity: 0.8;
			background-color: #e8e8e8;
		}
	}
}
</style>